import 'dart:convert';

import 'package:eplorex/infra/websocket_event_handler.dart';
import 'package:eplorex/infra/websocket_utils.dart';

import '../providers/user_context.dart';
import 'message_frame.dart';
import 'message_frame_type.dart';
import 'model/auth_message.dart';
import 'model/chat_message.dart';

typedef MessageCallBack = void Function(dynamic message);

class IMSdkClient {
  static final IMSdkClient _client = IMSdkClient();

  static List<MessageCallBack> callbacks = [];

  static IMSdkClient initSDK() {
    WebsocketUtils.initNetWork();
    WebsocketUtils.listen(WebsocketEventHandler());
    return _client;
  }

  static registerCallback(MessageCallBack callback) {
    callbacks.add(callback);
  }

  static unRegisterCallback(MessageCallBack callback) {
    callbacks.remove(callback);
  }

  static login() {
    _client._login();
  }

  void _login() {
    Header header = Header(
        type: MessageTypeEnum.auth.value,
        bizId: 1,
        contentType: 1,
        ts: DateTime.now().microsecond,
        seq: 0);
    LoginFrame loginFrame = LoginFrame(
        uid: UserContext.cxt()!.uid.toString(),
        sid: "",
        appId: "explorex",
        device: Device(deviceId: UserContext.deviceInfo!.deviceId));
    MessageFrame messageFrame = MessageFrame(header: header, body: loginFrame);
    WebsocketUtils()?.sendMessage(message: jsonEncode(messageFrame));
  }

  static void sendMessage(String senderId, String receiverId, int convType,
      int convId,int cmd, Object message,{String? uuid}) {
    _client._sendMessage(senderId, receiverId,uuid, convType, convId,cmd, message);
  }

  static void onMessage(Object message) {
    for (var element in callbacks) {
      element.call(message);
    }
  }

  void _sendMessage(String senderId, String receiverId, String? uuid,int convType, int cid,int cmd,
      Object message) {
    Header header = Header(
        type: MessageTypeEnum.message.value,
        bizId: 1,
        contentType: 1,
        ts: DateTime.now().microsecond,
        seq: 0);
    ChatMessage chatMessage = ChatMessage(
        senderId: senderId,
        receiverId: receiverId,
        cid: cid,
        uuid:uuid,
        cmd:cmd,
        convType: convType,
        message: message);
    MessageFrame messageFrame = MessageFrame(
        header: header, body: chatMessage);
    WebsocketUtils()?.sendMessage(message: jsonEncode(messageFrame));
    // 网络不通
  }
}
